<?php 
/*
   Copyright 2010, Sanket Parab

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This is part of the e-TAT Architecture Package and will be featured in the final e-TAT Application (Phase 1).
   
   Group class: Holds data on all Groups created by the instructor corresponding to a Course.
 */
class Group {
	/**
	 * Constructor
	 * @param $id ID of the Group
	 */
	function __construct($id) {
		$this->id = $id;
		$query = mysql_query("SELECT * FROM `group` WHERE `id` = '$id';") or die(mysql_error());
		$result = mysql_fetch_object($query);
		if($result != '') {
			$this->id = $result->id;
			$this->name = $result->name;
			$this->description = $result->description;
			$this->student_ids = explode(',',$result->student_ids);
			$this->course_id = $result->course_id;
			$this->code_name = $result->code_name;
			$this->groups_name = $result->groups_name;
			$this->svn = $result->svn;
			$this->wiki = $result->wiki;
			$this->forum = $result->forum;
			$this->issue = $result->issue;
			$this->file = $result->file;
		}
	}
	/**
	 * Update this group
	 */
	public function updateGroup() {
		if($this->student_ids[0] == '') { 
			$students = "NULL";
		} else {
			$students = implode(',',$this->student_ids);
		}
		$query = mysql_query("UPDATE `group` SET `name` = '$this->name', `description` = '$this->description', `student_ids` = '$students', `course_id` = '$this->course_id', `code_name` = '$this->code_name', `groups_name` = '$this->groups_name' WHERE `id` = '$this->id'") or die(mysql_error());
		return true;
	}
	/**
	 * Get count of all new forum posts added to this group
	 */
	public function getForumCount(){
		$query = mysql_query("SELECT * FROM `forum` WHERE `group_id` = '$this->id'") or die(mysql_error());
		$count = mysql_num_rows($query);
		return $count;
	}
	/**
	 * Get count of all new SVN commits added to this group
	 */
	public function getSVNCount(){
		$query = mysql_query("SELECT * FROM `svn` WHERE `group_id` = '$this->id'") or die(mysql_error());
		$count = mysql_num_rows($query);
		return $count;
	}
	/**
	 * Get count of all new wiki posts added to this group
	 */
	public function getWikiCount(){
		$query = mysql_query("SELECT * FROM `wiki` WHERE `group_id` = '$this->id'") or die(mysql_error());
		$count = mysql_num_rows($query);
		return $count;
	}
	/**
	 * Get count of all new issues added/modified to this group
	 */
	public function getIssueCount(){
		$query = mysql_query("SELECT * FROM `issue` WHERE `group_id` = '$this->id'") or die(mysql_error());
		$count = mysql_num_rows($query);
		return $count;
	}

	/**
	 * Get count of all new files added/modified to this group
	 */
	public function getFileCount(){
		$query = mysql_query("SELECT * FROM `file` WHERE `group_id` = '$this->id'") or die(mysql_error());
		$count = mysql_num_rows($query);
		return $count;
	}
	/**
	 * Returns the course to which this group belongs
	 */
	public function getCourse() {
		return new Course($this->course_id);
	}
	/**
	 * Returns an array of all student classes that belong to this group
	 */
	public function getAllStudents() {
		$query = mysql_query("SELECT * FROM `student` WHERE `group_id` = '$this->id'") or die(mysql_error());
		while($r = mysql_fetch_object($query)) {
			$students[] = new Student($r->id);
		}
		return $students;
	}
	/**
	 * Returns a single student class that belongs to this group
	 * @param $id requires the student id
	 */
	public function getStudent($id) {
		$query = mysql_query("SELECT * FROM `student` WHERE `group_id` = '$this->id' AND `id` = '$id';") or die(mysql_error());
		$result = mysql_fetch_object($query);
		if($result) {
			return new Student($result->id);
		} else {
			return false;
		}
	}
	/**
	 * Adds a new student to this group
	 * @param $data OBJECT ARRAY
	 * $data->name name of the student
	 * $data->email email address of the student
	 */
	public function addStudent($data) {
		$full_name = "'$data->name'";
		$email = "'$data->email'";
		$query = mysql_query("INSERT INTO `student` VALUES (NULL,$full_name,$email,$this->id);") or die(mysql_error());
		$student = $this->searchStudent($data);
		return $student->id;
	}

	/**
	 * Searches for students that belong to this group
	 * @param $data OBJECT ARRAY
	 * $data->email email address of the student
	 * $data->name name of the student
	 */
	public function searchStudent($data) {
		$full_name = $data->name;
		if(stristr($full_name,'---') == $full_name) { // Added as a bug fix. Google sometimes sends updates with --- as the user name.
			return false;
		}
		$len = strpos($data->email,'@')? strpos($data->email,'@') : strlen($data->email);
		$email = trim(substr($data->email,0,$len),'.');
		$names = explode(' ',strtolower(trim($full_name,"'`-")));
		$checks = "`full_name` LIKE '%$full_name%'";
		foreach($names as $n) { 
			if(strlen($n) >= 4) {
				$checks .= " OR `full_name` LIKE '%$n%'";
			}
		}
		$checks .= " OR `full_name` LIKE '%$email%' OR `email` LIKE '%$email%'";
		$query = mysql_query("SELECT * FROM `instructor` WHERE $checks") or die(mysql_error()); // Check if this is an Instructor's update. If yes then dont include it.
		$result = mysql_fetch_object($query);
		if($result) {
			return false;
		} else {
			$query = mysql_query("SELECT * FROM `student` WHERE `group_id` = '$this->id' AND ($checks);") or die(mysql_error());
			$result = mysql_fetch_object($query);
			if($result) { // Student found.
				return new Student($result->id);
			} else { // Student not found (Create new Student).
				return $this->addStudent($data);
			}
		}
	}
	/**
	 * Removes a student from the group. Also removes all feeds updated by the student.
	 * @param $id requires student id.
	 */
	public function deleteStudent($id) {
		$query = mysql_query("UPDATE `student` SET `visible` =  '0' WHERE `id`='$id'") or die(mysql_error());
		$query = mysql_query("DELETE FROM `forum` WHERE `author` = '$id'") or die(mysql_error());
		$query = mysql_query("DELETE FROM `file` WHERE `author` = '$id'") or die(mysql_error());
		$query = mysql_query("DELETE FROM `svn` WHERE `author` = '$id'") or die(mysql_error());
		$query = mysql_query("DELETE FROM `wiki` WHERE `author` = '$id'") or die(mysql_error());
		$query = mysql_query("DELETE FROM `issue` WHERE `author` = '$id'") or die(mysql_error());
		return true;
	}
	/**
	 * Removes this group from the course
	 */
	public function remove() {
		$this->course_id = '';
		$this->updateGroup();
		return true;
	}
	/**
	 * Updates all feeds belonging to this group
	 */
	public function updateFeeds() {
		$total['totals'] = 0;
		$total['group_name'] = $this->name;
		$total['forums'] = $this->parseForum();
		$total['svn'] = $this->parseSVN();
		$total['wiki'] = $this->parseWiki();
		$total['issue'] = $this->parseIssue();
		$total['file'] = $this->parseFile();
		$total['totals'] = array_sum($total);
		$query = mysql_query("UPDATE `group` SET
			`forum` = '$this->forum',
			`svn` = '$this->svn',
			`wiki` = '$this->wiki',
			`issue` = '$this->issue',
			`file` = '$this->file'
			WHERE `id` = '$this->id'") or die(mysql_error());
		return $total;
	}
	/**
	 * Parses the forum feed
	 */
	public function parseForum() {
		$forum_count = 0;
		$num = $latest_date == 0? 500 : 50;
		$msgs_url = "http://groups.google.com/group/$this->groups_name/feed/atom_v1_0_topics.xml?num=$num";
		$p1 = new Parser();
		$p1->parse($msgs_url);
		$t = $p1->getItems();
		foreach($t as $i) {
			$all[$i['UPDATED']] = $i;
		}
		$topics_url = "http://groups.google.com/group/$this->groups_name/feed/atom_v1_0_msgs.xml?num=$num";
		$p2 = new Parser();
		$p2->parse($topics_url);
		$m = $p2->getItems();
		foreach($m as $i) {
			$all[$i['UPDATED']] = $i;
		}
		if($all) {
			$items = array_reverse($all);
		}
		$x = 1;
		if($items) {
			foreach($items as $i) {
				$search->name = $i['AUTHOR']['NAME'];
				$search->email = $i['AUTHOR']['EMAIL'];
				$temp = substr($search->email,strpos($search->email,'@')+1);
				$author = $this->searchStudent($search);
				$url = $i['ID'];
				$title = addslashes($i['TITLE']);
				$summary = addslashes($i['SUMMARY']);
				$date = $i['UPDATED'];
				if($temp == 'googlecode.com') { // For checkign if it's an SVN/Wiki feed, inside the Forum feed.
					$full_comment = $i['SUMMARY'];
					$revision_full = substr($full_comment,strpos($full_comment,'Revision: ')+10);
					$revision = substr($revision_full,0,strpos($revision_full,'br>'));
					$url = "http://code.google.com/p/$this->code_name/source/detail?r=$revision";
					$author_full = substr($full_comment,strpos($full_comment,'Author: ')+8);
					$search->name = substr($author_full,0,strpos($author_full,'br>'));
					$search->email = '';
					$author = $this->searchStudent($search);
					$comment_part = substr($full_comment,strpos($full_comment,'Log: ')+5);
					$comment = addslashes(substr($comment_part,0,strpos($comment_part,'br>a ')));
					$content = addslashes(substr($full_comment,strpos($full_comment,'[link]/a>br>')+12));
					$is_wiki = strpos($content,'/wiki/') != false? true : false;
					$wiki_flag = false;
					if($author) {
						if($is_wiki == false) { // SVN feed.
							if($revision > $this->svn) {
								$this->svn = $revision;
								$query = mysql_query("INSERT INTO `svn` VALUES (
									NULL , '$date', '$this->id', '$url', '$revision', '$author->id', '$comment', '$content');") or die(mysql_error());
								if(!isset($this->svn_count)) {
									$this->svn_count = 1;
								} else {
									$this->svn_count++;
								}
							}
						} else { // Wiki feed.
							if($revision > $this->wiki) {
								$this->wiki = $revision;
								$query = mysql_query("INSERT INTO `wiki` VALUES (
									NULL , '$date', '$this->id', '$url', '$revision', '$author->id', '$comment', '$content');") or die(mysql_error());
								if(!isset($this->wiki_count)) {
									$this->wiki_count = 1;
								} else {
									$this->wiki_count++;
								}
							}
						}
					}
					$author = false;
				}
				if($author != false) { // Forum feed.
					if($date > $this->forum) { 
						$this->forum = $date;
						$query = mysql_query("INSERT INTO `forum` VALUES (
						NULL , '$this->id', '$date', '$author->id', '$url',
						'$title', '$summary');") or die(mysql_error());
						$forum_count++;
					} else {
						$query = mysql_query("SELECT * FROM `forum` WHERE `url` LIKE '$url' AND `group_id` = '$this->id'")
						or die(mysql_error());
						$result = mysql_fetch_object($query);
						if($result == '') {
							$query = mysql_query("INSERT INTO `forum` VALUES (
							NULL , '$this->id', '$date', '$author->id', '$url',
							'$title', '$summary');") or die(mysql_error());
							$forum_count++;
						}
					}
				}
			}
		}
		return $forum_count;
	}
	/**
	 * Parses the SVN feed
	 */
	public function parseSVN() {
		$svn_count = $this->svn_count? $this->svn_count : 0;
		$this->svns = 0;
		$feed_url = "http://code.google.com/feeds/p/$this->code_name/svnchanges/basic";
		$p = new Parser();
		$p->parse($feed_url);
		$items = $p->getItems();
		for($x = count($items)-1; $x >= 0; $x--) {
			$i = $items[$x];

			$date = $i['UPDATED'];
			$revision = substr(strrchr($i['ID'],'/'),1);
			$url = "http://code.google.com/p/$this->code_name/source/detail?r=$revision";
			$search->name = $i['AUTHOR']['NAME'];
			$search->email = $i['AUTHOR']['EMAIL'];
			$author = $this->searchStudent($search);
			$full_comment = $i['TITLE'];
			$comment = addslashes(substr($full_comment,strlen("Revision $revision:")));
			$content = addslashes($i['CONTENT']);
			$is_wiki = strpos($content,'/wiki/') != false? true : false;
			if($revision > $this->svn && $author != false && $is_wiki == false) {
				$this->svn = $revision;
				$query = mysql_query("INSERT INTO `svn` VALUES (
				NULL , '$date', '$this->id', '$url', '$revision', '$author->id', '$comment', '$content');") or die(mysql_error());
				$svn_count++;
			}
		}
		return $svn_count;
	}
	/**
	 * Parses the wiki feed
	 */
	public function parseWiki() {
		$wiki_count = $this->wiki_count? $this->wiki_count : 0;
		$feed_url = "http://code.google.com/feeds/p/$this->code_name/svnchanges/basic?path=/wiki/";
		$p = new Parser();
		$p->parse($feed_url);
		$items = $p->getItems();
		for($x = count($items)-1; $x >= 0; $x--) {
			$i = $items[$x];

			$date = $i['UPDATED'];
			$revision = substr(strrchr($i['ID'],'/'),1);
			$url = "http://code.google.com/p/$this->code_name/source/detail?r=$revision";
			$search->name = $i['AUTHOR']['NAME'];
			$search->email = $i['AUTHOR']['EMAIL'];
			$author = $this->searchStudent($search);
			$full_comment = $i['TITLE'];
			$comment = addslashes(substr($full_comment,strlen("Revision $revision:")));
			$content = addslashes($i['CONTENT']);
			$is_wiki = strpos($content,'/wiki/') != false? true : false;

			if($revision > $this->wiki && $author != false) {
				$this->wiki = $revision;
				$query = mysql_query("INSERT INTO `wiki` VALUES (
				NULL , '$date', '$this->id', '$url', '$revision', '$author->id', '$comment', '$content');") or die(mysql_error());
				$wiki_count++;
			}
		}
		return $wiki_count;
	}
	/**
	 * Parses the issue feed
	 */
	public function parseIssue() {
		$issue_count = 0;
		$feed_url = "http://code.google.com/feeds/p/$this->code_name/issueupdates/basic";
		$p = new Parser();
		$p->parse($feed_url);
		$items = $p->getItems();
		for($x = count($items)-1; $x >= 0; $x--) {
			$i = $items[$x];
			$date = $i['UPDATED'];
			$full_id = substr($i['ID'],strpos($i['ID'],'basic')+6);
			$pos = strpos($full_id,'/')? strpos($full_id,'/') : strlen($full_id);
			$issue_id = substr($full_id,0,$pos);
			$update_id = substr($full_id,$pos+1)? substr($full_id,$pos+1): "NULL";
			$update_url = $update_id != "NULL"? "#c$update_id" : '';
			$url = "http://code.google.com/p/$this->code_name/issues/detail?id=$issue_id$update_url";
			$title = addslashes(trim(substr($i['TITLE'],strpos($i['TITLE'],'"')+1),'")'));
			$description = addslashes($i['CONTENT']);
			$search->name = $i['AUTHOR']['NAME'];
			$search->email = $i['AUTHOR']['EMAIL'];
			$author = $this->searchStudent($search);
			if($date > $this->issue) {
				$this->issue = $date;
				$query = mysql_query("INSERT INTO `issue` VALUES (
				NULL , '$date', '$this->id', '$issue_id', '$update_id' , '$url', '$author->id', '$title', '$description');")
				or die(mysql_error());
				$issue_count++;
			}
		}
		return $issue_count;
	}
	/**
	 * Parses the files feed
	 */
	public function parseFile() {
		$query = mysql_query("UPDATE `file` SET `active` = '0' WHERE `group_id` = '$this->id'") or die(mysql_error());
		$file_count = 0;
		$feed_url = "http://code.google.com/feeds/p/$this->groups_name/downloads/basic";
		$p = new Parser();
		$p->parse($feed_url);
		$items = $p->getItems();
		foreach($items as $i) {
			$date = $i['UPDATED'];
			$search->name = $i['AUTHOR']['NAME'];
			$search->email = $i['AUTHOR']['EMAIL'];
			$author = $this->searchStudent($search);
			$file_name = substr($i['ID'],strpos($i['ID'],'basic/')+6);
			$file = rawurlencode($file_name);
			$url = "http://code.google.com/p/$this->groups_name/downloads/detail?name=$file";
			$title = addslashes($i['TITLE']);
			$content = addslashes($i['CONTENT']);

			$query = mysql_query("SELECT * FROM `file` WHERE `file_name` = '$file_name' AND `group_id` = '$this->id'") or die(mysql_error());
			$result = mysql_fetch_object($query);
			if($author != false) {
				if($result) {
					$query = mysql_query("UPDATE `file` SET `date`='$date',`url`='$url',
						`file_name`='$file_name',`author`='$author->id',`title`='$title',
						`content`='$content',`active`='1' WHERE `id` = '$result->id'") or die(mysql_error());
				} else {
					$this->file = $date;
					$query = mysql_query("INSERT INTO `file` VALUES (
					NULL , '$this->id', '$date', '$url', '$file_name', '$author->id', '$title', '$content', '1');") or die(mysql_error());
					$file_count++;
				}
			}
		}
		return $file_count;
	}
}